package job.manager.client.mb;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.model.SelectItem;
import javax.servlet.ServletContext;
import job.manager.db.ec.JobEB;
import job.manager.db.ec.ProfilesEB;
import job.manager.db.ec.TimeReportEB;
import job.manager.db.ec.TimeScheduleRowEB;
import job.manager.db.ec.UsersEB;
import job.manager.db.sb.JobRemote;
import job.manager.db.sb.ProfileRemote;
import job.manager.db.sb.TimeRemote;
import job.manager.db.sb.UserRemote;
import org.springframework.security.context.SecurityContextHolder;

/**
 *  The timeReport ManagedBean is responsible for connection to the Enterprise Beans
 *  and creating new TimeReport.
 *
 */
public class TimeReportMB {

    @EJB
    private TimeRemote timeBean;
    @EJB
    private JobRemote jobBean;
    @EJB
    private ProfileRemote profileBean;
    @EJB
    private UserRemote userBean;
    private String anvNamn;
    private UsersEB currentUser;
    private ProfilesEB userProfile;
    private String jobIdString;
    private int code;
    private Date date;
    private String time;
    private Calendar helpCal;
    private String comment;
    private int hour;
    private int minute;

    /** Creates a new instance of TimeReportMB */
    public TimeReportMB() {
        onInit();
    }

    @PostConstruct
    private void onInit() {
        problemSolver();
        anvNamn = SecurityContextHolder.getContext().getAuthentication().getName();
        currentUser = userBean.findUser(anvNamn);
        //if(!currentUser.getIsAdmin())
        userProfile = profileBean.getProfileInfo(currentUser.getProfileId());
        this.code = 0;
        date = new Date(System.currentTimeMillis());
        helpCal = new GregorianCalendar();
        helpCal.setTime(date);
        time = "" + helpCal.get(Calendar.HOUR_OF_DAY) + ":" + helpCal.get(Calendar.MINUTE);
        setTime(time);
        comment = "Skriv kommentar här";
    }

    //action create the timereport
    public void insertThe(ActionEvent arg){

            if (this.userProfile != null) {
            problemSolver();
            helpCal.setTime(date);
            helpCal.set(Calendar.HOUR, hour);
            helpCal.set(Calendar.MINUTE, minute);
            date = helpCal.getTime();
            TimeScheduleRowEB tRow = new TimeScheduleRowEB(null, date, comment);
            tRow = timeBean.insert(tRow);
            JobEB selectedJob = jobBean.getJob(Integer.parseInt(jobIdString));
            TimeReportEB report = new TimeReportEB(null, code, 0000);//Hård kod
            report.setJobId(selectedJob);
            report.setProfileId(userProfile);
            report.setScheduleRowId(tRow);
            report = timeBean.insert(report);
        }
    }

    //privides an link to the servlet that will show the user's timereports
    public String getHistoryLink() {
        this.problemSolver();
        ServletContext context = (ServletContext)FacesContext.getCurrentInstance().getExternalContext().getContext();
        String path = context.getContextPath();
        //add the servlet name
        path += "/pages/ReportTimeServlet?profileId=";
        UsersEB siteuser= this.getSiteUser();
        int profileId = 0;
        if( siteuser != null)
            profileId = siteuser.getProfileId();
        return path + profileId;
    }

    //checks witch user is logged in
    protected UsersEB getSiteUser() {
        this.problemSolver();
        String userNamn = SecurityContextHolder.getContext().getAuthentication().getName();
        return userBean.findUser(userNamn);
    }

    //spring security bug fix
    private void problemSolver() {
        if (this.userBean == null) {
            this.userBean = ConnectFactory.getUserBean();
        }

        if (this.profileBean == null) {
            this.profileBean = ConnectFactory.getProfileBean();
        }

        if (this.jobBean == null) {
            this.jobBean = ConnectFactory.getJobBean();
        }

        if (this.timeBean == null) {
            this.timeBean = ConnectFactory.getTimeBean();
        }
    }

    //set and get methods
    public String getAnvNamn() {
        return anvNamn;
    }

    public String getProfileInfo() {
        if (userProfile != null) {
            return userProfile.getName1() + " " + userProfile.getName2() + "<br/>Personnummer: " + userProfile.getNumber();
        } else {
            return "No profile info";
        }
    }

    public String getJobIdString() {
        return jobIdString;
    }

    public void setJobIdString(String jobIdString) {
        this.jobIdString = jobIdString;
    }

    public int getCode() {
        return this.code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        
        StringBuffer sb = new StringBuffer(time);
        StringBuffer sb2 = new StringBuffer(sb);
        int colIndex = sb.indexOf(":");
        sb2.delete(colIndex, sb2.length());
        sb.delete(0, colIndex);
        colIndex = sb.indexOf(":");
        if(colIndex != -1)
            sb.deleteCharAt(colIndex);
        String s1 = sb.toString();
        String s2 = sb2.toString();
        hour = Integer.parseInt(s2);
        minute = Integer.parseInt(s1);
        if(hour<10){
            this.time = "0" +hour;
        }
        else{
            this.time = "" +hour;
        }
        
        if(minute<10){
            this.time += ":0" +minute;
        }
        else{
            this.time += ":" +minute;
        }        
    }

    public String getComment() {
        return comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }

    //get the codes for the timereport
    public ArrayList<SelectItem> getCodes() {
        ArrayList<SelectItem> itemList = new ArrayList<SelectItem>();
        SelectItem a = new SelectItem();
        SelectItem b = new SelectItem();
        a.setLabel("Instämpling");
        a.setValue("1010");
        b.setLabel("Utstämpling");
        b.setValue("1020");
        itemList.add(a);
        itemList.add(b);
        return itemList;
    }

    //get a list of all jobs.
    public ArrayList<SelectItem> getJobList() {
        problemSolver();
        ArrayList<SelectItem> itemList = new ArrayList<SelectItem>();
        Collection<JobEB> jobList = jobBean.getAllJobs();
        if (jobList != null) {
            for (JobEB j : jobList) {
                SelectItem a = new SelectItem();
                a.setLabel(j.getName());
                a.setValue(j.getId().toString());
                itemList.add(a);
            }
        } else {
            SelectItem a = new SelectItem();
            a.setLabel("");
            a.setValue(null);
            itemList.add(a);
        }

        return itemList;
    }
}
